from q import Queue

import random

class Printer(object):
    def __init__(self, ppm) -> None:
        self.pagerate = ppm
        self.currentTask = None
        self.timeRemaining = 0

    def tick(self):
        if self.currentTask != None:
            self.timeRemaining = self.timeRemaining - 1
            if self.timeRemaining <= 0:
                self.currentTask = None

    def busy(self):
        if self.currentTask != None:
            return True
        else:
            return False

    def startNext(self, newtask):
        self.currentTask = newtask
        self.timeRemaining = newtask.getPage() * 60 / self.pagerate


class Task(object):
    def __init__(self, time) -> None:
        self.timestamp = time
        self.page = random.randrange(1, 21)

    def getStamp(self):
        return self.timestamp

    def getPages(self):
        return self.page

    def waitTime(self, currenttime):
        return currenttime - self.timestamp

def newPrintTask():
    num = random.randrange(1, 181)
    
    if num == 180:
        return True
    else:
        return False


def simulation(numSecond, pagesPerMinute):
    
    labprinter = Printer(pagesPerMinute)
    printQueue = Queue()
    waitingtime = []

    for currentSecond in range(numSecond):
        
        if newPrintTask():
            task = Task(currentSecond)
            printQueue.enqueue(task)

        if (not labprinter.busy()) and (not printQueue.isEmpty()):
            nexttask = printQueue.dequeue()
            waitingtime.append(
                nexttask.waitTime(currentSecond)
            )

        labprinter.startNext(nexttask)
        labprinter.tick()

    averageWait = sum(waitingtime) / len(waitingtime)
    print(
        "Average Wait %6.2f secs %3d tasks remaining." % (averageWait, printQueue.size())
    )


